package com.weixin.reflection.normal;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @ClassName ReflectionTest
 * @Description reflection
 * @date 2022/2/18 11:07
 * @author: wx
 * @Version 1.0
 */

public class ReflectionTest {


    @Test
    public void PersonTest() {
        Person person = new Person("weiXin");
        System.out.println(person.getUsername());

    }

    @Test
    public void PersonTest01() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        Class<Person> cls = Person.class;
        //反射获取构造器，用构造器实例化对象
        Constructor<Person> constructor = cls.getConstructor(String.class);
        Person person1 = constructor.newInstance("TomSoa");
        System.out.println(person1.toString());
        //反射操纵字段
        Field field = cls.getDeclaredField("username");
        field.setAccessible(true);
        field.set(person1,"EricToms");
        System.out.println(person1);
        //反射操作方法
        Method concatUsername = cls.getDeclaredMethod("concatUsername", String.class, String.class);
        concatUsername.setAccessible(true);
        Object invoke = concatUsername.invoke(person1, "Tom", "Soa"); //相当于person1.ConcatUsername
        System.out.println(invoke.toString());
    }

    @Test
    public void reflection03() throws ClassNotFoundException {
        //Class对应一个运行时类
        //获取类
        Class<Person> cls = Person.class;
        System.out.println(cls);
        //通过运行时对象获取class实例
        Person person = new Person();
        Class<? extends Person> aClass = person.getClass();
        System.out.println(aClass);

        //调用Class的静态方法
        Class<?> aClass1 = Class.forName("com.weixin.reflection.normal.Person");
        System.out.println(aClass1);
    }
}
